import { ThunkAction } from "redux-thunk";
import { ChannelActions } from "@actions/channelActions";
import { AppState } from "@src/index";
import { ChannelTypes } from "@store/types/channelTypes";
import { channelsRequest } from "@requests/channel";
import { AxiosError } from "axios";

export namespace ChannelCreators {
    export const requestChannel = (): ThunkAction<
        Promise<ChannelActions.Actions>,
        AppState,
        any,
        ChannelActions.Actions
    > => async (dispatch) => {
        dispatch({ type: ChannelTypes.REQUEST_CHANNEL })
        try {
            const response = await channelsRequest()
            return dispatch({
                type: ChannelTypes.REQUEST_CHANNEL_SUCCESS,
                payload: {
                    channels: response.data.channels
                }
            })
        } catch (error) {
            if (error instanceof AxiosError) {
                return Promise.reject(
                    dispatch({
                        type: ChannelTypes.REQUEST_CHANNEL_ERROR,
                        error: error.response?.data.message
                    })
                )
            }
            return Promise.reject(error)
        }
    }
}